from metamake import task, shell, path, bootstrap

bootstrap("Makefile")

@task(default=True)
def build():
    """builds everything into a source distribution"""
    buildpyx()
    shell("python setup.py sdist")

@task
def buildpyx():
    """builds all .pyx extensions"""
    shell("python setup.py build_ext --inplace")
    # clean up the resulting c files of any absolute paths on this system
    for cfile in path("stockpyle").listdir("*.c"):
        fd = open(cfile, "r")
        contents = fd.read()
        fd.close()
        fd = open(cfile, "w+")
        clean_content = contents.replace(path(".").abspath(), "")
        fd.write(clean_content)
        fd.close()

@task
def install():
    """installs the latest built module"""
    tarballs = sorted(path("dist").listdir("*.tar.gz"))
    if not tarballs:
        build()
        tarballs = sorted(path("dist").listdir("*.tar.gz"))
    latest = tarballs[-1]
    shell("easy_install --upgrade %s" % latest)

@task
def release():
    """releases this code + documentation to pypi"""
    shell("python setup.py register")
    shell("python setup.py sdist upload")

@task
def clean():
    """cleans all intermediate files"""
    if path("MANIFEST").exists():
        path("MANIFEST").remove()
    if path("build").exists():
        path("build").rmtree()
    if path("dist").exists():
        path("dist").rmtree()
    patterns = ["*.coverage", "*.sqlite", "*.csv", "*.prof", "*.egg-info", "*.so", "*.dll", "*.c", "*.pyc"]
    for p in patterns:
        for d in [".", "tests", "stockpyle"]:
            if path(d).exists():
                for f in path(d).listdir(p):
                    if f.isdir():
                        f.rmtree()
                    else:
                        f.remove()